package org.springblade.modules.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.modules.admin.mapper.UserWeixinMapper;
import org.springblade.modules.admin.entity.UserWeixin;
import org.springblade.modules.admin.service.UserWeixinService;

@Service
@Slf4j
public class UserWeixinServiceImpl extends BaseServiceImpl<UserWeixinMapper, UserWeixin> implements UserWeixinService {

    private final static String WEI_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private final static String WEI_USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=";

    @Value("${weixin.appId}")
    private String appId;

    @Value("${weixin.appSecret}")
    private String appSecret;

    @Override
    public void updateUserSubscribe() {
        Map<String, Object> map = new HashMap<>(16);
        map.put("grant_type", "client_credential");
        map.put("appid", appId);
        map.put("secret", appSecret);
        String s = HttpUtil.get(WEI_ACCESS_TOKEN_URL, map);
		log.info("<---------------------------- {WECHAT_ACCESS_TOKEN:}"+s+"------------------------------->");
		Map resultMap = JSON.parseObject(s, Map.class);
		String accessToken = Convert.toStr(resultMap.get("access_token"));
        List<UserWeixin> result = new ArrayList<>();
        Boolean nextPage = true;
        int current = 1;
        int size = 100;
        do {
            Query query = new Query();
            query.setCurrent(current);
            query.setSize(size);
            IPage<UserWeixin> page = Condition.getPage(query);
            IPage<UserWeixin> userWxIPage = page.setRecords(baseMapper.selectUserWxPage(page));
            List<UserWeixin> userWxList = page.getRecords();
            Map<String, Object> body = new HashMap<>(1);
            List<Map<String, String>> user_list = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(userWxList)) {
                userWxList.forEach(e -> {
                    Map<String, String> item = new HashMap<>(2);
                    item.put("openid", e.getOpenid());
                    item.put("lang", "zh_CN");
                    user_list.add(item);
                });
                body.put("user_list", user_list);
                String resultStr = HttpUtil.createPost(WEI_USER_INFO_URL + accessToken).body(JSONObject.toJSONString(body)).execute().body();
				log.info("<---------------------------- {USER_INFO:}"+resultStr+"------------------------------->");
                JSONObject resultJson = JSONObject.parseObject(resultStr);
                JSONArray user_info_list = resultJson.getJSONArray("user_info_list");
                for (int i = 0; i < user_info_list.size(); i++) {
                    JSONObject item = user_info_list.getJSONObject(i);
                    userWxList.forEach(e -> {
                        if (item.getString("openid").equals(e.getOpenid())) {
							e.setSubscribe(item.getInteger("subscribe"));
							result.add(e);
                        }
                    });
                }
            }
            nextPage = current < userWxIPage.getPages();
            current++;
        } while (nextPage);

		super.updateBatchById(result);
    }
}

